package com.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.portal.constant.RedisConst;
import com.portal.enums.UserStatus;
import com.portal.exception.Assert;
import com.portal.model.entity.User;
import com.portal.model.vo.LoginRequest;
import com.portal.model.vo.UserVo;
import com.portal.result.impl.BusinessCode;
import com.portal.service.UserService;
import com.portal.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
* @author 61073
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-10-09 15:33:07
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public ResponseEntity<?> login(LoginRequest param) {
        // ===========验证码校验===============
        // 获取用户输入的key; 也就是访问验证码接口返回的：【 "user:code:0bd1e8c49e9d4594b6ce5e01f846446a"】
        String key = param.getKey();
        String redisCode = "1234";// fixme 测试方便写死 stringRedisTemplate.opsForValue().get(key);
        // 判断验证码是否为空
        Assert.error(redisCode == null, BusinessCode.INVALID_VERIFICATION);
        // 判断验证码是否一致
        Assert.error(!redisCode.equals(param.getCode()), BusinessCode.INVALID_VERIFICATION);

        // 校验完，删除验证码
        stringRedisTemplate.delete(key);

        // 根据账号查询用户: param.getAccount()
        Wrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getAccount, param.getAccount());
        User userdb = userMapper.selectOne(wrapper);
        Assert.error(userdb == null, BusinessCode.USER_NOT_EXIST);

        // 判断密码是否正确
        boolean matches = passwordEncoder.matches(param.getPassword(), userdb.getPassword());
        Assert.error(!matches, BusinessCode.PASSWORD_ERROR);

        // 判断账号是否可用
        Assert.error(userdb.getState() != UserStatus.ACTIVE.getKey(), BusinessCode.USER_FROZEN_ERROR);

        return ResponseEntity.ok(userdb);
    }

    @Cacheable(cacheNames = RedisConst.USER_DETAIL, keyGenerator = "keyGenerator")
    @Override
    public UserVo findById(String userId) {
        User user = userMapper.selectById(userId);

        //  org. springframework. beans. BeanUtils
        //UserVo userVo = new UserVo();
        //BeanUtils.copyProperties(user, userVo);

        // cn. hutool. core. bean. BeanUtil
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        return userVo;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePwd = encoder.encode("123456");
        // $2a$10$APgisI3QAeZtcjVO8yPVOeZqQ2uCNcPHXWMemJ7jhxRt.EVpAR9e2
        // $2a$10$sWAK3J.feVbwBc0Luy2Qk.XWYO3U2Vf/1Lg3jQdHdVf/0n89P8BAO
        System.out.println("encodePwd = " + encodePwd);

        boolean matches = encoder.matches("12345", "$2a$10$sWAK3J.feVbwBc0Luy2Qk.XWYO3U2Vf/1Lg3jQdHdVf/0n89P8BAO");
        System.out.println("matches = " + matches);
    }

    @Override
    public long registCheck(String columnName, String columnValue) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(columnName, columnValue);
        return this.count(wrapper);
    }
}




